<template>
  <div class="newsublist">
    <!-- 库房列表 -->
    <div class="store-list">
      <!-- 筛选 -->
      <search-store @change="search_data" v-if="this.role[0].sort >= 80"></search-store>
      <div class="add-store">
        <el-button
          type="primary"
          icon="el-icon-plus"
          @click="addStore"
          v-if="this.role[0].sort === 100"
        >新建仓库</el-button>
      </div>
      <el-table :data="listData" stripe :header-cell-style="getRowClass" v-loading="loading">
        <el-table-column prop="num" label="序号"></el-table-column>
        <el-table-column prop="store_level" label="库房等级">
          <template slot-scope="scope">
            {{scope.row.store_level == '0' ? '零级' : null}}
            {{scope.row.store_level == '1' ? '一级' : null}}
            {{scope.row.store_level == '2' ? '二级' : null}}
            {{scope.row.store_level == '3' ? '三级' : null}}
            {{scope.row.store_level == '4' ? '四级' : null}}
            {{scope.row.store_level == '5' ? '五级' : null}}
          </template>
        </el-table-column>
        <el-table-column prop="name" label="库房名称"></el-table-column>
        <el-table-column prop="address" label="库房详细地址"></el-table-column>
        <el-table-column prop="parentName" label="上级库位名称">
          <template slot-scope="scope">{{getParentName(scope.row.super_id)}}</template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="text"
              size="small"
              @click="handleInsert(scope.row)"
              title="新增仓库"
              v-has-permission="btn[0]"
            >
              <img src="/static/image/common/add.png" alt />
            </el-button>
            <el-button
              type="text"
              size="small"
              @click="handleView(scope.row)"
              title="查看"
              v-has-permission="btn[2]"
            >
              <img src="/static/image/common/preview.png" alt />
            </el-button>
            <el-button
              type="text"
              size="small"
              v-if="scope.row.store_level !== 1"
              @click="handleEdit(scope.row)"
              title="编辑"
              v-has-permission="btn[1]"
            >
              <img src="/static/image/common/edit.png" alt />
            </el-button>

            <el-button
              type="text"
              size="small"
              v-if="scope.row.store_level !== 1"
              @click="handleDelete(scope.row)"
              title="删除"
              v-has-permission="btn[3]"
            >
              <img src="/static/image/common/delete.png" alt />
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <page-list :size.sync="pageSize" :total="total" :current.sync="currentPage" @change="getSub"></page-list>
    </div>
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      width="420px"
      class="center"
      @close="resetPeopleForm"
    >
      <!-- 编辑 -->
      <!-- 新增 -->
      <create-sub :form="peopleForm" @hide="hideDialog" :title="title" :flag="flag" ref="createSub"></create-sub>
    </el-dialog>
    <el-dialog
      title="仓库预览"
      :visible.sync="dialogVisibleShow"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      width="420px"
      class="center"
    >
      <view-sub :people-form="peopleForm" :list-config="listConfig"></view-sub>
    </el-dialog>
    <!--删除弹出框-->
    <el-dialog
      :close-on-click-modal="false"
      title="删除内容"
      class="center"
      id="delect"
      width="420px"
      :visible.sync="deleteDialog"
      :modal-append-to-body="false"
    >
      <span style="color: #444;font-size: 14px;display: inline-block;margin: 20px 0px 0px 0px;">
        <img src="/static/image/device/delect2.png" style="vertical-align: middle;" />
        确定要删除
        <i
          style="font-style: normal;color:rgb(235, 56, 56);"
        >{{this.deleteObject.name}}</i> 吗？
      </span>
      <div slot="footer" class="dialog-footer" style="text-align: right;">
        <el-button
          type="primary"
          @click="sureDelete"
          style="padding: 5px 25px;background-color:#EB3838;border-color:#EB3838;"
        >确 定</el-button>
        <el-button
          @click="deleteDialog = false"
          style="padding: 5px 25px;background: rgb(178, 186, 211);border:rgb(178, 186, 211);color: rgb(255, 255, 255);"
        >取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import createSub from "./createSub";
import ViewSub from "./ViewSub";
import { mapGetters } from "vuex";
import Config from "@/config";
import location from "@/util/location";
import PageList from "@/components/PageList";
import SearchStore from "./SearchStore.vue";
import {regionData, REGION_DATA} from 'static/js/regionData'

// import
export default {
  name: "CommunitySub",
  props: {
    btn: {
      type: Array
    }
  },
  components: {
    createSub,
    ViewSub,
    PageList,
    SearchStore
  },
  data() {
    return {
      // 表格数据
      listData: [],
      // 弹出框
      dialogVisible: false,
      dialogVisibleShow: false,
      deleteDialog: false,
      // 删除对象
      deleteObject: {},
      title: "",
      peopleForm: {},
      listConfig: [], // 保险配置属性
      // 分页
      total: 0,
      currentPage: 1,
      pageSize: 15,
      inputs: 15,
      // loading
      loading: false,
      filterList: [],
      flag: false,
      parentList: [],
      configList: []
    };
  },
  created() {
    this.resetPeopleForm();
    this.getSub();
  },
  methods: {
    // 父级数字展示变化
    getParentName(value) {
      //  console.log(value)
      // console.log(this.parentList.find((res, index) => res.id))
      var ojb = this.parentList.find((res, index) => res.id === value);
      if (ojb) {
        return ojb.name;
      } else {
        return "华强";
      }
    },
    // 筛选条件
    search_data(name) {
      if (!name) return this.getSub();
      // console.log(store_id);
      const url = `${
        Config.DEVICE_MANAGE_URL
      }/storehouses/query_sub_by_name?page=${this.currentPage - 1}&size=${
        this.pageSize
      }&devtype=${Config.objType.devtype}&name=${name}`;
      var param = {};
      if (this.role[0].sort === 93) {
        param.housetype = "test";
      } else if (this.role[0].sort !== 100) {
        param.housetype = "official";
      }
      this.$http.get(url, param).then(res => {
        res.array = res.array || [];
        res.array.push(res.self);
        this.dispath(res);
      });
    },
    /**
     * 从后台获取列表
     * */
    getSub() {
      const url = `${
        Config.DEVICE_MANAGE_URL
      }/storehouses/query_common?page=${this.currentPage - 1}&size=${
        this.pageSize
      }`;
      var params = {};
      if (this.role[0].sort === 93) {
        params.housetype = "test";
      } else if (this.role[0].sort == 60 && this.district.districtType === 2) {
        params.province = this.district.provinceCode;
        params.house_owner = this.user.company;
      } else if (this.role[0].sort == 60 && this.district.districtType === 3) {
        params.city = this.district.cityCode;
        params.house_owner = this.user.company;
      } else if (this.role[0].sort !== 100) {
        params.housetype = "official";
        params.house_owner = this.user.company;
      }
      this.$http.get(url, params).then(res => {
        this.dispath(res);
        const url = `${Config.DEVICE_MANAGE_URL}/storehouses/query_batch_by_id`;
        this.$http
          .get(url, { ids: this.listData.map(res => res.super_id).join(",") })
          .then(res => {
            // console.log(res)
            this.parentList = res.array;
          });
      });
    },
    dispath(res) {
      this.total = res.allcount;
      if (res.array.length) {
        res.array.map((item, i) => {
          if (this.currentPage === 1) {
            item.num = i + 1;
          } else {
            item.num = (this.currentPage - 1) * this.pageSize + i + 1;
          }
        });
        this.listData = res.array;
        this.loading = false;
      } else {
        this.listData = res.array;
        this.loading = false;
      }
    },
    /**
     * 表头添加背景颜色
     * */
    getRowClass({ row, column, rowIndex, columnIndex }) {
      if (rowIndex === 0) {
        return "background:#fafbfc";
      } else {
        return "";
      }
    },
    //  admin新增一级仓库
    addStore() {
      this.title = "新建仓库";
      this.dialogVisible = true;
      this.flag = true;
    },
    /**
     * 新增仓库
     * */
    handleInsert(item) {
      // console.log(item)
      this.title = "新增仓库";
      this.resetPeopleForm();
      this.peopleForm.id = item.id;
      this.peopleForm.store_level = item.store_level;
      this.dialogVisible = true;
      this.flag = true;
    },
    /**
     * 重置用户
     * */
    resetPeopleForm() {
      this.flag = false;
      this.peopleForm.name = "";
      this.peopleForm.address = "";
      this.peopleForm.selectedOptions = [];
      this.peopleForm.storeconfig = [];
    },
    /**
     * 编辑用户
     * */
    handleEdit(row) {
      console.log(row)
      this.title = "仓库编辑";
      this.peopleForm = JSON.parse(JSON.stringify(row));
      // 获取仓库属性
      this.peopleForm.selectedOptions = [row.province, row.city, row.district];
      this.dialogVisible = true;
      this.flag = true;
      console.log(this.peopleForm);
    },

    /**
     * 用户预览
     * */
    handleView(row) {
      console.log(row)
      // var area = "";
      // area = location.gpsChange(row.lon, row.lat);
      // var myGeo = new BMap.Geocoder();
      // myGeo.getLocation(area, rs => {
      //   console.log(area, rs)
      //   var addComp = rs.addressComponents;
      //   row.province = addComp.province;
      //   row.city = addComp.city;
      //   row.district = addComp.district;
      //   row.street = addComp.street;
      // });

      row.provinceName = row.province ? REGION_DATA["86"][row.province] : '';
      row.cityName = row.city ? REGION_DATA[row.province][row.city] : '';
      row.districtName = row.district ?  REGION_DATA[row.city][row.district] : '';
      // console.log(row)
      this.title = "仓库预览";
      this.peopleForm = null;
      this.peopleForm = row;
      // console.log(this.peopleForm)
      this.listConfig = [];
      // 获取仓库属性
      this.$nextTick(() => {
        const url = `${Config.DEVICE_MANAGE_URL}/storehouse_config/query_common?storehouse_id=${row.id}`;
        this.$http
          .get(url)
          .then(res => {
            this.listConfig = res.array;
          })
          .catch(e => {
            console.log(e);
          });
      });

      this.dialogVisibleShow = true;
    },
    /**
     * 删除
     * */
    handleDelete(row) {
      console.log(row);
      this.deleteObject = row;
      this.deleteDialog = true;
    },
    sureDelete() {
      const url = `${Config.DEVICE_MANAGE_URL}/storehouse_config/both_delete`;
  
      this.$http
        .post(url, {
          storehouse_id: this.deleteObject.id
        })
        .then(res => {
          this.$message.success("删除成功");
          this.deleteDialog = false;
          this.deleteObject = {};
          this.getSub();
        })
        .catch(e => {
          this.$message.error(`${e}`);
        });
    },
    /**
     * 关掉dialog
     * */
    hideDialog(success) {
      if (success === "cancel") {
        this.dialogVisible = false;
        this.flag = false;
        return;
      }
      if (success === true) {
        this.$message.success("保存成功");
        this.dialogVisible = false;
        this.flag = false;
        this.getSub();
        return;
      }
      this.$message.success("保存失败");
    }
  },
  computed: {
    ...mapGetters("user", {
      district: "getDistrict",
      role: "getRole",
      user: "getUser"
    })
  }
};
</script>

<!-- Add 'scoped' attribute to limit CSS to this component only -->
<style lang='scss' scoped>
@import "../../../../../static/scss/common";
.newsublist {
  .date-picker /deep/ .el-input--prefix .el-input__inner {
    padding-left: 30px;
  }
  .el-form-item.img-name {
    margin: 10px 0 10px 0;
  }
  .form .el-input__inner {
    height: 28px !important;
    line-height: 28px !important;
    border: 1px solid #e4e4e4;
    padding: 0 0 0 10px !important;
    .el-icon-time {
      line-height: 0;
    }
    .el-range-separator {
      line-height: 25px;
    }
  }
  .form.el-row {
    margin-bottom: 20px;
    &:last-child {
      margin-bottom: 0;
    }
  }
  .store-list {
    width: 100%;
    height: auto;
    background: $white;
    .add-store {
      display: inline-block;
      float: right;
      margin-top: -46px;
      margin-right: 30px;
    }
  }
  #delect /deep/ .el-dialog {
    padding-bottom: 0px;
  }
}
</style>
